package com.mediacloud.app.newsmodule.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.GlideUtils;
import com.mediacloud.app.assembly.util.ImageKitKt;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.fbnavsk.SecondFloorHandlerKt;
import com.mediacloud.app.model.HistoryModel;
import com.mediacloud.app.model.LookHistoryModel;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.nav2.fragment.HqyNavFragment;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.topic.HorizonalRecyclerViewDividerXV2;
import com.mediacloud.app.newsmodule.fragment.baoliao.TransUtils;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsLowApi;
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker;
import com.mediacloud.app.newsmodule.utils.spider.SpiderKit;
import com.mediacloud.app.newsmodule.view.ComponentContainer;
import com.mediacloud.app.quanzi.DongTaiDetailActivity;
import com.mediacloud.app.quanzi.HuaTiDetailActivityV4;
import com.mediacloud.app.quanzi.model.DongTaiBean;
import com.mediacloud.app.quanzi.model.HuaTiBean;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.controller.BaseController;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.view.XSmartRefreshLayout;
import com.mediaclound.appfactnet.utils.RxTransformerUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zimeiti.details.MediaAuthorDetailActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ZhanWeiFragment extends HqyNavFragment implements androidx.lifecycle.Observer<SpiderKit.SpiderHuaTiAttention> {

    private final String TAG = ZhanWeiFragment.class.getSimpleName();
    private List<HuaTiBean> mDataBean = new ArrayList<>();
    private List<Map<String, String>> mList = new ArrayList<>();
    RecyclerView rv, rv2;
    TextView tvNothing;
    XSmartRefreshLayout refreshLayout;
    ImageView vNothing;
    HistoryAdapter historyAdapter;
    JoinedAdapter joinedAdapter;
    /**
     * 组件的
     */
    protected ComponentContainer componetContainer = null;
    private LinearLayout headerViewContainer;
    NewsListDataInvoker dataInvoker = null;
    BaseDataInvokeCallBack  dataCallback = null;
    private ArrayList<ComponentItem> componentItems   = new ArrayList<ComponentItem>();

    private int mPageIndex  = 1;
    private int PAGE_SIZE  = 20;
    protected String catalogID;
    protected CatalogItem catalogItem;
    @Override
    public int getLayoutResID() {
        return R.layout.fragment_zhanwei;
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        if (getFragmentArguments() != null) {
            saveInstanceArguments = getFragmentArguments();
            catalogID = saveInstanceArguments.getString("id");
            catalogItem = saveInstanceArguments.getParcelable("catalog");
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments.getString("id");
            catalogItem = saveInstanceArguments.getParcelable("catalog");
        }
        if (catalogItem == null) catalogItem = new CatalogItem();
    }

    @Override
    public void initView() {
        LiveEventBus.get(
                SpiderKit.SPIDER_HUATI_ATTENTION,
                SpiderKit.SpiderHuaTiAttention.class
        ).observe(this, this);
        SecondFloorHandlerKt.navPaddingTopMatch(this);
        refreshLayout = findViewById(R.id.refreshLayout);
        //最近浏览
        rv = findViewById(R.id.zhanwei_rv_topic);
        //我加入的操场
        rv2 = findViewById(R.id.zhanwei_rv_topic2);
        tvNothing = findViewById(R.id.zhanwei_tv_nothing);
        vNothing = findViewById(R.id.zhanwei_v_nothing);
        if (!TextUtils.isEmpty(AppFactoryGlobalConfig.getAppServerConfigInfo(requireContext()).getNoContent())) {
            ImageKitKt.loadX(vNothing, AppFactoryGlobalConfig.getAppServerConfigInfo(requireContext()).getNoContent(),
                    2, 0, false, null);
        }
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                getComponentList();
                getHistoryAndJoinList();
            }
        });
        initComponentContainer();
    }
    protected void initComponentContainer() {
        headerViewContainer=findViewById(R.id.headerViewContainer);
        if (componetContainer==null) {
            componetContainer = new ComponentContainer(getActivity(),getCurrentICMP26Holder());
        }
        headerViewContainer.addView(componetContainer, 0);
        initDataInvoker();
        getComponentList();
    }
    protected void initDataInvoker() {
        dataCallback =new  BaseNewsDataInvokeCallBack();
        dataInvoker = new NewsListDataInvoker(dataCallback);
    }
    public void  getComponentList() {
        if (dataInvoker!=null) {
            dataInvoker.getContentListWithAd(catalogID, mPageIndex, PAGE_SIZE, null);
        }
    }
    public abstract class BaseDataInvokeCallBack<T extends BaseMessageReciver> implements DataInvokeCallBack<T> {
        @Override
        public void fault(Object object) {
        }
    }
    public class BaseNewsDataInvokeCallBack extends BaseDataInvokeCallBack<ArticleListData> {

        @SuppressWarnings("unchecked")
        public void success(ArticleListData result) {
            if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                return;
            }
            if (result != null && result.state) {

                if (mPageIndex == 1) {

                    if (componetContainer!=null&&
                            componetContainer.componentListItemStyleAdaptor!=null) {
                        componetContainer.componentListItemStyleAdaptor.clearEvent();
                    }
                    componentItems.clear();
                    if (result.componentItems!=null){
                        addComponent(result.componentItems);
                    }
                }
            }
            if (mPageIndex == 1) {
                if (componentItems == null || componentItems.size() == 0) {
                    if (headerViewContainer.getVisibility() == View.VISIBLE) {
                        headerViewContainer.setVisibility(View.GONE);
                    }
                } else {
                    if (headerViewContainer.getVisibility() == View.GONE) {
                        headerViewContainer.setVisibility(View.VISIBLE);
                    }
                }
            }

        }
    }

    protected void addComponent( List<ComponentItem> componentItemList) {
        if (componentItemList == null || componentItemList.size() == 0) {
            componetContainer.clearOld();
            return;
        }
        ArrayList<ComponentItem> data = new  ArrayList<ComponentItem>();
        data.addAll(componentItemList);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            componetContainer.updateComponent(data);
        }
    }
    /*@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) onResume();
    }*/

    @Override
    public void onResume() {
        super.onResume();
        getHistoryAndJoinList();
    }

    private void getHistoryAndJoinList() {
        UserInfo userInfo=UserInfo.getUserInfo(getContext());
        if(!userInfo.isLogin()){
            if (historyAdapter!=null) {
                mList.clear();
                historyAdapter.notifyDataSetChanged();
            }
            tvNothing.setVisibility(View.VISIBLE);
            rv.setVisibility(View.GONE);

            if (joinedAdapter!=null) {
                mDataBean.clear();
                joinedAdapter.notifyDataSetChanged();
            }
            vNothing.setVisibility(View.VISIBLE);
            rv2.setVisibility(View.GONE);
            refreshLayout.finishRefresh();
            return;
        }
        //获取最近浏览数据
        Map<String, Object> map = new HashMap<>();
        map.put("source", 15);
        map.put("is_filter_copy",1);
        DataInvokeUtil.getZiMeiTiApi().getHistoryList(userInfo.getUserid(), map)
                .compose(TransUtils.fastJSonTransform(LookHistoryModel.class)).compose(RxTransformerUtils.schedulersTransformer())
                .subscribe(new BaseController().new BaseObserver<LookHistoryModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                        getCompositeDisposable().add(d);
                    }

                    @Override
                    public void onNext(LookHistoryModel mode) {
                        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                            return;
                        }
                        refreshLayout.finishRefresh();
                        mList.clear();
                        if (mode.isState()) {
                            for (HistoryModel bean : mode.getData().getMeta()) {
                                if (null != bean) {
                                    Map<String, String> map = new HashMap<>();
                                    map.put("id", bean.getId() + "");
                                    map.put("source_id", bean.getSource_id());
                                    map.put("logo", bean.getLogo());
                                    map.put("title", bean.getTitle());
                                    map.put("summary", bean.getSummary());
                                    map.put("url", bean.getUrl());
                                    mList.add(map);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                            return;
                        }
                        refreshLayout.finishRefresh();
                        if (mList==null||mList.size()==0) {
                            tvNothing.setVisibility(View.VISIBLE);
                            rv.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                            return;
                        }
                        if (mList.size() != 0) {
                            tvNothing.setVisibility(View.GONE);
                            rv.setVisibility(View.VISIBLE);
                            if (historyAdapter == null) {
                                historyAdapter = new HistoryAdapter(mList);
                                rv.setLayoutManager( new LinearLayoutManager(
                                        requireContext(),
                                        LinearLayoutManager.HORIZONTAL,
                                        false
                                ));
                                rv.addItemDecoration(new HorizonalRecyclerViewDividerXV2(
                                        getResources().getDimensionPixelSize(R.dimen.dimen12),
                                        getResources().getDimensionPixelSize(R.dimen.dimen15),
                                        getResources().getDimensionPixelSize(R.dimen.dimen12)));
                                rv.setAdapter(historyAdapter);
                            } else {
                                historyAdapter.notifyDataSetChanged();
                            }
                        } else {
                            tvNothing.setVisibility(View.VISIBLE);
                            rv.setVisibility(View.GONE);
                        }
                    }
                });
        //获取我加入的操场数据
      //  SpiderCmsApi.getSpiderCmsApiJson(getContext()).getJoinTopic(userInfo.getUserid())
        SpiderCmsLowApi.getSpiderCmsLowApiJson(getContext()).getJoinTopic(userInfo.getUserid())
                .observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        getCompositeDisposable().add(d);
                    }

                    @Override
                    public void onNext(JSONObject jsonObject) {
                        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                            return;
                        }
                        refreshLayout.finishRefresh();
                        mDataBean.clear();
                       try {
                           Gson gson = new Gson();
                           TopicBean topicBean = gson.fromJson(jsonObject.toString(), new TypeToken<TopicBean>() {}.getType());
                           if (topicBean != null && topicBean.data != null && topicBean.data.pageRecords != null) {
                               mDataBean.addAll(topicBean.data.pageRecords);
                           }
                       }catch (Exception e){
                           e.printStackTrace();
                       }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                            return;
                        }
                        refreshLayout.finishRefresh();
                        if (mDataBean==null||mDataBean.size()==0) {
                            vNothing.setVisibility(View.VISIBLE);
                            rv2.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                            return;
                        }
                        if (null != mDataBean && mDataBean.size() > 0) {
                            vNothing.setVisibility(View.GONE);
                            rv2.setVisibility(View.VISIBLE);
                            if (joinedAdapter == null) {
                                joinedAdapter = new JoinedAdapter(mDataBean);
                                rv2.setLayoutManager(new LinearLayoutManager(getContext()));
                                rv2.setAdapter(joinedAdapter);
                            } else {
                                joinedAdapter.notifyDataSetChanged();
                            }
                        } else {
                            vNothing.setVisibility(View.VISIBLE);
                            rv2.setVisibility(View.GONE);
                        }
                    }
                });
    }


    //最近浏览Adapter
    class HistoryAdapter extends RecyclerView.Adapter<HistoryHolder> {

        private List<Map<String, String>> mList;

        public HistoryAdapter(List<Map<String, String>> mList) {
            this.mList = mList;
        }

        @NonNull
        @Override
        public HistoryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new HistoryHolder(View.inflate(getContext(), R.layout.item_zhanwei_topic, null));
        }

        @Override
        public void onBindViewHolder(@NonNull HistoryHolder holder, int position) {
            GlideUtils.loadUrl(mList.get(position).get("logo"),holder.picture);
            holder.picture.setOnClickListener(v -> {
                HuaTiBean huaTiBean = new HuaTiBean();
                try {
                    if (!TextUtils.isEmpty(mList.get(position).get("source_id"))) {
                        huaTiBean.setId(Long.parseLong(mList.get(position).get("source_id")));
                    }
                    huaTiBean.setImg(mList.get(position).get("logo"));
                    huaTiBean.setName(mList.get(position).get("title"));
                    huaTiBean.setSummary(mList.get(position).get("summary"));
                    huaTiBean.setShareUrl(mList.get(position).get("url"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                HuaTiDetailActivityV4.startActvity(getContext(), huaTiBean);
            });
            holder.title.setText(mList.get(position).get("title"));
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }
    }

    class HistoryHolder extends RecyclerView.ViewHolder {

        ImageView picture;
        TextView title;

        public HistoryHolder(@NonNull View itemView) {
            super(itemView);
            picture = itemView.findViewById(R.id.zhanwei_iv_picture);
            title = itemView.findViewById(R.id.zhanwei_tv_title);
        }
    }

    //我加入的操场Adapter
    class JoinedAdapter extends RecyclerView.Adapter<JoinedHolder> {

        private List<HuaTiBean> mList;

        public JoinedAdapter(List<HuaTiBean> list) {
            mList = list;
        }

        @NonNull
        @Override
        public JoinedHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new JoinedHolder(View.inflate(getContext(), R.layout.item_zhanwei_topic2, null));
        }

        @Override
        public void onBindViewHolder(@NonNull JoinedHolder holder, int position) {
            HuaTiBean topBean = mList.get(position);
            GlideUtils.loadUrl(topBean.getImg(),holder.topPicture);
            holder.topTitle.setText(topBean.getName());
            String count = new DecimalFormat("#,###").format(topBean.getMemberCount());
            SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(count);
            spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#D43D3D")), 0, count.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.topViral.setText(spannableStringBuilder.append(" 人加入"));
            holder.topDetail.setOnClickListener(v -> {
                HuaTiDetailActivityV4.startActvity(getContext(), topBean);
            });
            DongTaiBean contentBean = topBean.getLatestPublishDynamic();
            if (topBean.getLatestPublishDynamic() == null) {
                holder.clContent.setVisibility(View.GONE);
                return;
            }
            holder.clContent.setOnClickListener(v -> {
                Intent intent = new Intent();
                intent.setClass(getContext(), DongTaiDetailActivity.class);
                intent.putExtra("tieZiBean", contentBean);
                startActivity(intent);
            });
            holder.contentHead.setOnClickListener(v -> {
                if (contentBean.getSelfMediaInfoMeta() != null) {
                    MediaAuthorDetailActivity.start(getContext(), contentBean.getSelfMediaInfoMeta().getUserId());
                }
            });

            if (contentBean.getSelfMediaInfoMeta() != null) {
                holder.contentName.setText(contentBean.getSelfMediaInfoMeta().getUserNickName());
                FunKt.load(holder.contentHead, contentBean.getSelfMediaInfoMeta().getUserImage());
            }
            holder.contentTitle.setText(contentBean.getContent());
            Glide.with(getContext()).load(contentBean.getLogo()).into(holder.contentPicture);
            holder.contentComment.setText(StringUtils.toTenThousand(contentBean.getCommentCount()) + "跟帖");
            holder.contentViral.setText(StringUtils.toTenThousand(contentBean.getPraiseCount()) + "点赞");
            holder.contentTime.setText(contentBean.getPublishDate());
        }

        @Override
        public int getItemCount() {
            return mDataBean.size();
        }
    }

    class JoinedHolder extends RecyclerView.ViewHolder {
        ConstraintLayout clContent;
        ImageView topPicture, contentPicture;
        CircleImageView contentHead;
        TextView topTitle, topViral, topDetail, contentName, contentTitle, contentComment, contentViral, contentTime;

        public JoinedHolder(@NonNull View itemView) {
            super(itemView);
            topPicture = itemView.findViewById(R.id.zhanwei_v_top_picture);
            topTitle = itemView.findViewById(R.id.zhanwei_tv_top_title);
            topViral = itemView.findViewById(R.id.zhanwei_tv_top_viral);
            topDetail = itemView.findViewById(R.id.zhanwei_tv_top_detail);
            clContent = itemView.findViewById(R.id.zhanwei_cl_content);
            contentHead = itemView.findViewById(R.id.zhanwei_v_content_head);
            contentName = itemView.findViewById(R.id.zhanwei_tv_content_name);
            contentTitle = itemView.findViewById(R.id.zhanwei_tv_content_title);
            contentPicture = itemView.findViewById(R.id.zhanwei_v_content_picture);
            contentComment = itemView.findViewById(R.id.zhanwei_tv_content_comment);
            contentViral = itemView.findViewById(R.id.zhanwei_tv_content_viral);
            contentTime = itemView.findViewById(R.id.zhanwei_tv_content_time);
        }
    }


    public static class TopicBean {
        public int state;
        public boolean success;
        public String message;
        public DataBean data;
    }

    public static class DataBean {
        public List<HuaTiBean> pageRecords;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (componetContainer != null) {
            componetContainer.dispose();
            if (componetContainer.componentListItemStyleAdaptor!=null){
                componetContainer.componentListItemStyleAdaptor.clearEvent();
            }
        }
        LiveEventBus.get(
                SpiderKit.SPIDER_HUATI_ATTENTION,
                SpiderKit.SpiderHuaTiAttention.class
        ).removeObserver(this);
    }

    @Override
    public void onChanged(SpiderKit.SpiderHuaTiAttention spiderHuaTiAttention) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        getHistoryAndJoinList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeLoginStatus(LoginEvent loginEvent) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }

        if (UserInfo.isLogin(requireContext()) || loginEvent.type == LoginEvent.LoginOut) {
            getHistoryAndJoinList();
        }
    }
}
